import AgoraRTM from 'agora-rtm'

// 简单的事件发射器实现
class SimpleEventEmitter {
  constructor() {
    this.events = {}
  }
  
  on(event, listener) {
    if (!this.events[event]) {
      this.events[event] = []
    }
    this.events[event].push(listener)
  }
  
  emit(event, ...args) {
    if (this.events[event]) {
      this.events[event].forEach(listener => listener(...args))
    }
  }
  
  off(event, listener) {
    if (this.events[event]) {
      this.events[event] = this.events[event].filter(l => l !== listener)
    }
  }
}

class RTMManager extends SimpleEventEmitter {
  constructor() {
    super()
    this.client = null
    this.options = null
  }
  
  async init(options) {
    this.options = options
    
    try {
      console.log('Initializing RTM with options:', options)
      
      // RTM SDK v2.x 使用 new AgoraRTM.RTM() 方式初始化
      if (AgoraRTM.RTM) {
        this.client = new AgoraRTM.RTM(options.appId, options.userId.toString())
      } else if (typeof AgoraRTM.createInstance === 'function') {
        this.client = AgoraRTM.createInstance(options.appId)
      } else {
        throw new Error('Unable to initialize AgoraRTM client')
      }
      
      // RTM v2.x 登录方式
      await this.client.login({
        token: options.token
      })
      console.log('RTM login successful')
      
      // RTM v2.x 订阅频道消息
      await this.client.subscribe(options.channel)
      console.log('RTM channel subscribed:', options.channel)
      
      // 监听消息 - 确保事件名称正确
      this.client.addEventListener('message', (eventArgs) => {
        console.log('RTM message received:', eventArgs)
        try {
          const data = JSON.parse(eventArgs.message)
          console.log('Parsed RTM data:', data)
          this.emit('rtmMessage', data)
        } catch (e) {
          console.error('Failed to parse RTM message:', e)
          console.error('Raw message:', eventArgs.message)
        }
      })
      
      // 监听连接状态变化
      this.client.addEventListener('status', (eventArgs) => {
        console.log('RTM status changed:', eventArgs)
      })
      
    } catch (error) {
      console.error('RTM initialization error:', error)
      throw error
    }
  }
  
  async sendText(text) {
    if (!this.client) return
    
    const message = {
      type: 'input_text',
      text,
      uid: this.options.userId,
      ts: Date.now(),
      is_final: true
    }
    
    console.log('Sending RTM message:', message)
    await this.client.publish(this.options.channel, JSON.stringify(message))
    
    // 立即显示用户消息
    this.emit('rtmMessage', message)
  }
  
  async destroy() {
    if (this.client) {
      try {
        await this.client.unsubscribe(this.options.channel)
        await this.client.logout()
        console.log('RTM destroyed successfully')
      } catch (error) {
        console.error('RTM destroy error:', error)
      }
      this.client = null
    }
  }
}

export const rtmManager = new RTMManager()
